<?php 
class User extends Module {
    private $user_id;
    private $position_ids = array();
    private $is_admin = 0;
    
    public function login() {
        if ( ! isset($_SESSION)) {
            session_start();
        }
        $logined = false;
        $username = '';
        $password = '';
        $error = '';
        
        //print_r($_SESSION);
        
        if ( ! isset($_SESSION['user_id'])) {
            if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
                $username = tos_http_post('username');
                $password = tos_http_post('password');
                if ($username && $password && $user_id = $this->model('user')->authenticate($username, $password)) {
                    $_SESSION['user_id'] = $user_id;
                    $logined = true;
                } else {
                    $error = 'Username or Password is not right.';
                }
            }
        } else {
            $logined = true;
        }
        //var_dump($username);
        if ($logined) {
            $this->user_id = (int) $_SESSION['user_id'];
            return true;
            
        } else {
            $view = $this->view('user_login', array(
                'username'  => $username,
                'error'     => $error
            
            ));
            return $view;
        }
    }
    
    public function is_admin() {
        if (0 === $this->is_admin) {
            $position_ids = $this->position_ids();
            $admin_position_id = $this->model('user')->admin_position_id();
            
            if (in_array($admin_position_id, $position_ids)) {
                $this->is_admin = true;
            } else {
                $this->is_admin = false;
            }
        }
        
        return $this->is_admin;
    }
    
    private function position_ids() {
        if ( ! $this->position_ids) {
            $this->position_ids = $this->model('user')->position_ids($this->user_id);
        }
        return $this->position_ids;
    }
    
    public function logout() {
        if (isset($_SESSION)) {
            unset($_SESSION['user_id']);
            session_destroy();
        }
        echo 'logout';
        exit();
    }
    
    public function get_user_id() {
        if ($this->user_id) {
            return $this->user_id;
        } else {
            return false;
        }
    }
}
?>